package com.wb3.organizer.service;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.wb3.organizer.dao.AppointmentDAO;
import com.wb3.organizer.model.Account;
import com.wb3.organizer.model.Appointment;

public class AppointmentService {
	
	private AppointmentDAO dao;

	public AppointmentDAO getDao() {
		return dao;
	}

	public void setDao(AppointmentDAO dao) {
		this.dao = dao;
	}
	
	public void saveAppointment(Appointment appointment){
		dao.save(appointment);
	}
	
	public void updateAppointment(Appointment appointment){
		dao.update(appointment);
	}
	
	public void deleteAppointment(Appointment appointment){
		dao.delete(appointment);
	}
	
	public List<Appointment> getAppointmentByTime(Account account, Date date, String viewType){
		List<Appointment> appointments = dao.getAllByAccount(account);
		List<Appointment> appointmentsOut = new ArrayList<Appointment>();
		
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		int day = calendar.get(Calendar.DATE);
	    int month = calendar.get(Calendar.MONTH) + 1;
	    int year = calendar.get(Calendar.YEAR);
	    int weekOfMonth = calendar.get(Calendar.WEEK_OF_MONTH);
	    
	    for(int i=0; i<appointments.size(); i++){
	    	Date appointmentDate = appointments.get(i).getAppointmentDate();
	    	calendar.setTime(appointmentDate);
	    	int a_day = calendar.get(Calendar.DATE);
		    int a_month = calendar.get(Calendar.MONTH) + 1;
		    int a_year = calendar.get(Calendar.YEAR);
		    int a_weekOfMonth = calendar.get(Calendar.WEEK_OF_MONTH);
		    
		    boolean takeIt = false;
		    if(viewType.equalsIgnoreCase("day")){
		    	if(day == a_day && month == a_month && year == a_year){
		    		takeIt = true;
		    	}
		    }
		    if(viewType.equalsIgnoreCase("week")){
		    	if(month == a_month && year == a_year && weekOfMonth == a_weekOfMonth){
		    		takeIt = true;
		    	}
		    }
		    if(viewType.equalsIgnoreCase("month")){
		    	if(month == a_month && year == a_year){
		    		takeIt = true;
		    	}
		    }
		    if(viewType.equalsIgnoreCase("year")){
		    	if(year == a_year){
		    		takeIt = true;
		    	}
		    }
		    
		    if(takeIt){
		    	appointmentsOut.add(appointments.get(i));
		    }
	    }
	    
		return appointmentsOut;
	}
	
	public Appointment getAppointment(int app_id){
		return dao.getAppointmentById(app_id);
	}
}
